package com.miaoxun.service.impl;


import com.basemapper.BasicMapper;
import com.miaoxun.dao.RoleMapper;
import com.miaoxun.dao.RoleMenuMapper;
import com.miaoxun.dao.UserRoleMapper;
import com.miaoxun.domain.entity.Role;
import com.miaoxun.domain.entity.RoleMenu;
import com.miaoxun.domain.param.RoleParam;
import com.miaoxun.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    protected BasicMapper getMapper() {
        return roleMapper;
    }



    @Override
    public List<Role> listByUserId(Long id) {
        List<Long> rolesIds = userRoleMapper.listRoleId(id);
        List<Role> roles = getAll();
        for (Role roleDO : roles) {
            roleDO.setRoleSign("false");
            for (Long roleId : rolesIds) {
                if (Objects.equals(roleDO.getRoleId(), roleId)) {
                    roleDO.setRoleSign("true");
                    break;
                }
            }
        }
        return roles;
    }

    @Override
    public boolean updateRole(RoleParam param) {

        Role role = new Role();
        role.setGmtModified(new Date());
        role.setRemark(param.getRemark());
        role.setRoleId(param.getRoleId());
        role.setRoleName(param.getRoleName());
        boolean r = update(role);

        List<Long> menuIds = param.getMenuIds();
        Long roleId = role.getRoleId();
        roleMenuMapper.removeByRoleId(roleId);
        List<RoleMenu> rms = new ArrayList();
        for (Long menuId : menuIds) {
            RoleMenu rmDo = new RoleMenu();
            rmDo.setRoleId(roleId);
            rmDo.setMenuId(menuId);
            rms.add(rmDo);
        }
        if (rms.size() > 0) {
            roleMenuMapper.batchSave(rms);
        }
        return r;
    }
}
